Appendix K — Assignment 6

Author

phonchi

Published

May 28, 2023

K.1 (1) Which of the following statement is False?

  1. Python does not have private attributes. Instead, you use naming conventions to design classes that encourage correct use.

  2. Each new class you create can provide an __init__ method that specifies how to initialize an object’s data attributes.

  3. We can access the attribute of the class using the dot notation.

  4. If we access an attribute starting with _, an error will occur.

Ans: Double click to answer the question

  1. Actually, by convention, Python programmers know that any attribute name beginning with an underscore (_) is for a class’s internal use only. Even when we use this convention, attributes are always accessible.

K.2 (2) Which of the following term describes the “has a” relationship between two classes?

  1. Composition

  2. Inheritance

  3. Polymorphism

  4. Encapsulation

Ans: Double click to answer the question

K.3 (3) Which of the following statement is False?

  1. The self is used to represent the instance of the class in Python; if it is included in the method definition, it must come first before any other parameters.

  2. When calling an instance method in Python, self must be passed explicitly and it must come first before any other arguments.

  3. Any variable prefixed with self is available to every method in the class.

  4. A class definition begins with the keyword class followed by the class’s name and a colon (:).

Ans: Double click to answer the question

  1. We do not have to pass it, it will be passed implicitly.

K.4 (4) When we call the print() function and use an object as the argument, which special method will be called first?

  1. __add__

  2. __repr__

  3. __str__

  4. __init__

Ans: Double click to answer the question

K.5 (5) Which of the following function can be used to check whether an object belongs to a specific class or not?

  1. type()

  2. isinstance()

  3. dir()

  4. id()

Ans: Double click to answer the question

K.6 (6) Considering the following code cell. Try to modify the integer class so that when calling the show() function, it will not show the decimal point and the decimal part.

class floating:
    def __init__(self, num):
        self.num = num
    def show(self):
        print(f'{self.num:.1f}')

class integer(floating):
    def __init__(self, num):
        super().__init__(num)
    # Your code here
    def show(self):
        print(f'{self.num:d}')
egg = floating(3.53)
egg.show()
spam = integer(3)
spam.show()
3.5
3

K.7 (7) Modify the above classes so that we can add the objects from the integer and the objects from the floating class together.

class floating:
    def __init__(self, num):
        self.num = num
    # Your code here
    def show(self):
        print(f'{self.num:.1f}')
    
    def __add__(self, other):
        return self.num + other.num

class integer(floating):
    def __init__(self, num):
        super().__init__(num)
        
    def show(self):
        print(f'{self.num:d}')
egg = floating(3.53)
spam = integer(3)


print(spam + egg)
6.529999999999999

K.8 (8) You may notice that the above calculation is not correct in the math sense, why? Try to import a built-in class in Python so that the numbers can be represented exactly. In addition, calculate 3 + 3.53 exactly using the class.

Hint: You may use Copilot to give you suggestion

Since floating point representation is not exact, so there are some rounding errors.

# Try to import a class in python so that the numbers can be represented exactly
from decimal import Decimal

# Calculate 3 + 3.53 exactly
egg = Decimal('3.53')
spam = Decimal('3')
print(egg + spam)
6.53

K.9 (9) Design a triangle class that has two attributes, base and height and satisfies the following properties:

  1. Create a constructor that accepts base and height from the user.
  2. Using the naming convention to declare the two attributes as private data so that an error occurs when the user directly accesses these two attributes using dot notation.
  3. Add getter (get_base_height()) and setter(set_base_height) to the class so that the two attributes can be set and get simultaneously via these methods.
  4. Create a method area() for the class that returns the area of the triangle.
  5. When the user prints out the triangle object, show the base and height of the triangle.
class trinagle:
    def __init__(self, base, height):
        self.__base = base
        self.__height = height
    def get_base_height(self):
        return self.__base, self.__height
    def set_base_height(self, base, height):
        self.__height = height
        self.__base = base
    def area(self):
        return self.__base * self.__height / 2
    def __str__(self):
        return f'Triangle: base = {self.__base}, height = {self.__height}'
t1 = trinagle(3, 4)
print(t1.area())
b, h = t1.get_base_height()
print(b, h)
t1.set_base_height(7, 24)
print(t1)
6.0
3 4
Triangle: base = 7, height = 24

K.10 (10) Design a RightTriangle class by inheriting from the above class and modifying the class so that only valid base and height can be set. Otherwise, you should raise an exception.

Hint: You can raise an exception using the statement raise ValueError('Invalid base and height')

class RightTriangle(trinagle):
    def __init__(self, base, height):
        self.set_base_height(base, height)
    def set_base_height(self, base, height):
        if self.valid(base, height):
            self.__base = base
            self.__height = height
        else:
            raise ValueError('Invalid base and height')
    def valid(self, base, height):
        # The first condition is optional
        if ((base**2 + height**2)**0.5 == int((base**2 + height**2)**0.5)) and (base > 0 or height > 0):
            return True
        else:
            return False
try:
    print(RightTriangle(3, 4))
    print(RightTriangle(7, 24))
    print(RightTriangle(3, 5))
    print(RightTriangle(-1, -1))
except:
    print('An error occured')
An error occured